package com.itheima.reggie.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chm
 * @version 1.0.0 v
 * @date 2022-08-13 21:31
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    //自动注入接收消息类
    @Autowired
    private DishFlavorService dishFlavorService;

    //保存菜品基本信息到dish中
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
          this.save(dishDto);
        //菜品的id
        Long dishId = dishDto.getId();
        //口味id
        List<DishFlavor> flavors = dishDto.getFlavors();

//运用stream流
        flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());



        //保存口味到菜品中
       dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void pageByParams(Page<DishDto> dishDtoPage, DishDto dishDto) {

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
//查询菜品进本信息，
        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //查询口味信息
        LambdaQueryWrapper<DishFlavor>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新表的信息
      this.updateById(dishDto);
      //清理口味i和菜品相对应的数据
        LambdaQueryWrapper<DishFlavor>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();

//运用stream流
        flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());


        //把之前的口味数据添加进来
        List<DishFlavor> flavors1 = dishDto.getFlavors();

        dishFlavorService.saveBatch(flavors1);


    }
}
